<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

// 获取用户信息
const userStore = useUserStore()
const currentUserId = computed(() => userStore.userInfo?.id || '')

// 状态变量
const showSuccessDialog = ref(false)
const showReturnLocationDialog = ref(false) // 归还位置选择对话框
const successTitle = ref('操作成功')
const successMessage = ref('')
const filterStatus = ref('可用') // 默认筛选可用单车
const filterType = ref('')
const isBorrowMode = ref(true) // 借用模式
const isSelectingLocation = ref(false) // 位置选择模式
const hasSelectedLocation = ref(false) // 是否已在地图上选择了位置
const myBorrowedBikes = ref<any[]>([]) // 我借用的单车列表
const availableBikes = ref<any[]>([]) // 可用单车列表
const selectedBike = ref<any>(null) // 当前选中的单车
const returnAddress = ref('') // 归还地址
const bikeToReturn = ref<any>(null) // 要归还的单车
const loading = ref(false) // 加载状态

// 地图和图层引用
let view: MapView | null = null
let bikeLayer: FeatureLayer | null = null
let selectedBikeOID: number | null = null
let tempGraphic: Graphic | null = null
let newLocation: Point | null = null // 新的位置点

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})

// 加载可用单车列表
const loadAvailableBikes = async () => {
  if (!bikeLayer) return

  loading.value = true
  try {
    // 查询可用单车
    const query = bikeLayer.createQuery()
    let whereClause = "Status = '可用'"

    // 根据类型筛选
    if (filterType.value) {
      whereClause += ` AND BikeType = '${filterType.value}'`
    }

    query.where = whereClause
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await bikeLayer.queryFeatures(query)
    availableBikes.value = results.features.map((feature) => ({
      ...feature.attributes,
      geometry: feature.geometry,
    }))
  } catch (error) {
    console.error('加载可用单车失败:', error)
    ElMessage.error('加载可用单车失败')
  } finally {
    loading.value = false
  }
}

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'bikeMapDiv',
      map: map,
      center: [116.3, 39.9], // 北京的经纬度
      zoom: 10,
    })

    // 创建单车点要素图层
    bikeLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/rDRhdC4brwj3FLD5/arcgis/rest/services/cycleFeaturelayer/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
      renderer: {
        type: 'simple',
        symbol: new SimpleMarkerSymbol({
          color: [0, 112, 255],
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
          size: 12,
        }),
      },
    })

    // 添加图层到地图
    map.add(bikeLayer)

    // 添加点击要素事件
    if (view?.popup) {
      view.popup.autoCloseEnabled = false // 禁用自动弹出
    }
    view.on('click', (event) => {
      // 如果是位置选择模式，设置新位置
      if (isSelectingLocation.value) {
        // 移除之前的临时标记
        if (tempGraphic && view) {
          view.graphics.remove(tempGraphic)
        }

        // 获取点击位置
        newLocation = view!.toMap(event) as Point

        // 创建新的临时标记
        tempGraphic = new Graphic({
          geometry: newLocation,
          symbol: new SimpleMarkerSymbol({
            color: [255, 0, 0],
            outline: {
              color: [255, 255, 255],
              width: 2,
            },
            size: 12,
          }),
        })

        // 添加临时标记到地图
        view!.graphics.add(tempGraphic)

        // 标记已选择位置
        hasSelectedLocation.value = true

        // 显示位置选择对话框
        showReturnLocationDialog.value = true
        // 提示用户已成功选择位置
        ElMessage.success('已成功选择归还位置，请继续完成地址信息')
        return
      }

      // 如果不是借用模式，不执行选择操作
      if (!isBorrowMode.value) return

      // 构建查询参数
      const query = bikeLayer!.createQuery()
      query.outFields = ['*']
      query.distance = 1000
      query.units = 'meters'
      query.returnGeometry = true
      query.geometry = view!.toMap(event)
      query.spatialRelationship = 'intersects'

      // 执行查询
      bikeLayer!.queryFeatures(query).then((results) => {
        const feature = results.features[0]
        if (feature) {
          // 获取要素的属性
          const attributes = feature.attributes
          selectedBikeOID = attributes.OBJECTID

          // 检查单车是否可用
          if (attributes.Status !== '可用') {
            ElMessage.warning(`该单车当前状态为${attributes.Status}，不可借用`)
            return
          }

          // 保存选中的单车信息
          selectedBike.value = {
            BikeId: attributes.BikeId || '',
            BikeType: attributes.BikeType || '',
            NowAddress: attributes.NowAddress || '',
            Status: attributes.Status || '',
            BatteryLevel: attributes.BatteryLevel || '',
            OBJECTID: attributes.OBJECTID,
            TotalUsageCount: attributes.TotalUsageCount || '0',
          }

          // 显示借用确认对话框
          showBorrowConfirm()
        }
      })
    })

    // 初始筛选可用单车
    filterBikes()

    // 加载可用单车列表
    loadAvailableBikes()

    // 加载我借用的单车
    loadMyBorrowedBikes()
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 筛选单车
const filterBikes = () => {
  if (!bikeLayer) return

  let whereClause = '1=1' // 默认显示所有

  // 根据状态筛选
  if (filterStatus.value) {
    whereClause += ` AND Status = '${filterStatus.value}'`
  }

  // 根据类型筛选
  if (filterType.value) {
    whereClause += ` AND BikeType = '${filterType.value}'`
  }

  // 应用筛选
  bikeLayer.definitionExpression = whereClause

  // 更新可用单车列表
  loadAvailableBikes()
}

// 加载我借用的单车
const loadMyBorrowedBikes = async () => {
  if (!bikeLayer) return

  try {
    // 查询当前用户借用的单车
    const query = bikeLayer.createQuery()
    query.where = `CurrentUseUserId = '${currentUserId.value}' AND Status = '使用中'`
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await bikeLayer.queryFeatures(query)
    myBorrowedBikes.value = results.features.map((feature) => ({
      ...feature.attributes,
      geometry: feature.geometry,
    }))
  } catch (error) {
    console.error('加载借用单车失败:', error)
    ElMessage.error('加载借用单车失败')
  }
}

// 显示借用确认对话框
const showBorrowConfirm = () => {
  if (!selectedBike.value) return

  ElMessageBox.confirm(
    `确定要借用这辆${selectedBike.value.BikeType}吗？\n单车ID: ${selectedBike.value.BikeId}\n地址: ${selectedBike.value.NowAddress}`,
    '借用确认',
    {
      confirmButtonText: '确认借用',
      cancelButtonText: '取消',
      type: 'info',
    },
  )
    .then(() => {
      borrowBike()
    })
    .catch(() => {
      // 取消借用
      selectedBike.value = null
      selectedBikeOID = null
    })
}

// 借用单车
const borrowBike = async () => {
  if (!bikeLayer || !selectedBike.value || selectedBikeOID === null) {
    ElMessage.error('未找到要借用的单车')
    return
  }

  try {
    // 准备更新的属性
    const now = new Date()
    const borrowTime = now.toLocaleString()

    // 创建更新要素
    const updateFeature = new Graphic({
      attributes: {
        OBJECTID: selectedBikeOID,
        Status: '使用中',
        CurrentUseUserId: currentUserId.value,
        BorrowTime: borrowTime,
      },
    })

    // 更新要素
    const results = await bikeLayer.applyEdits({
      updateFeatures: [updateFeature],
    })

    if (results.updateFeatureResults && results.updateFeatureResults.length > 0) {
      successTitle.value = '借用成功'
      successMessage.value = `您已成功借用单车！\n单车ID: ${selectedBike.value.BikeId}\n借用时间: ${borrowTime}`
      showSuccessDialog.value = true

      // 刷新图层
      bikeLayer.refresh()

      // 刷新借用列表
      loadMyBorrowedBikes()

      // 刷新可用单车列表，移除已借用的单车
      loadAvailableBikes()

      // 重置选中状态
      selectedBike.value = null
      selectedBikeOID = null
    } else {
      ElMessage.error('借用单车失败')
    }
  } catch (error) {
    console.error('借用单车时出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 开始归还单车流程
const startReturnBike = (bike: any) => {
  if (!bikeLayer) {
    ElMessage.error('单车图层未初始化')
    return
  }

  // 保存要归还的单车信息
  bikeToReturn.value = bike

  // 进入位置选择模式
  isSelectingLocation.value = true

  // 重置位置选择状态
  hasSelectedLocation.value = false

  // 初始化归还地址为当前地址
  returnAddress.value = bike.NowAddress || ''

  // 提示用户必须先在地图上选择位置
  ElMessage.info('请先在地图上点击选择归还位置，然后再完善地址信息')
}

// 取消位置选择
const cancelLocationSelection = () => {
  // 移除临时标记
  if (tempGraphic && view) {
    view.graphics.remove(tempGraphic)
  }

  // 重置状态
  isSelectingLocation.value = false
  hasSelectedLocation.value = false
  newLocation = null
  tempGraphic = null
  showReturnLocationDialog.value = false
  bikeToReturn.value = null
}

// 确认归还单车
const confirmReturnBike = async () => {
  if (!bikeLayer || !bikeToReturn.value) {
    ElMessage.error('单车信息不完整')
    return
  }

  // 验证是否在地图上选择了位置
  if (!hasSelectedLocation.value || !newLocation) {
    ElMessage.warning('请先在地图上选择归还位置')
    return
  }

  // 验证是否输入了地址
  if (!returnAddress.value) {
    ElMessage.warning('请输入归还地址')
    return
  }

  try {
    const bike = bikeToReturn.value

    // 计算使用次数增加
    const currentCount = parseInt(bike.TotalUsageCount || '0')
    const newCount = currentCount + 1

    // 创建更新要素
    const updateFeature = new Graphic({
      // 只有在用户选择了新位置时才更新位置，否则保留原位置
      geometry: newLocation || bike.geometry,
      attributes: {
        OBJECTID: bike.OBJECTID,
        Status: '可用',
        CurrentUseUserId: '',
        BorrowTime: '',
        TotalUsageCount: String(newCount),
        NowAddress: returnAddress.value, // 更新地址
      },
    })

    // 更新要素
    const results = await bikeLayer.applyEdits({
      updateFeatures: [updateFeature],
    })

    if (results.updateFeatureResults && results.updateFeatureResults.length > 0) {
      // 关闭位置选择对话框
      showReturnLocationDialog.value = false

      // 显示成功信息
      successTitle.value = '归还成功'
      successMessage.value = `您已成功归还单车！\n单车ID: ${bike.BikeId}\n归还地址: ${returnAddress.value}`
      showSuccessDialog.value = true

      // 清理临时标记
      if (tempGraphic && view) {
        view.graphics.remove(tempGraphic)
      }

      // 重置状态
      isSelectingLocation.value = false
      newLocation = null
      tempGraphic = null
      bikeToReturn.value = null

      // 刷新图层
      bikeLayer.refresh()

      // 刷新借用列表
      loadMyBorrowedBikes()

      // 刷新可用单车列表，添加新归还的单车
      if (isBorrowMode.value) {
        loadAvailableBikes()
      }
    } else {
      ElMessage.error('归还单车失败')
    }
  } catch (error) {
    console.error('归还单车时出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 归还单车（直接启动归还流程）
const returnBike = async (bike: any) => {
  if (!bikeLayer) {
    ElMessage.error('单车图层未初始化')
    return
  }

  // 直接启动归还流程
  startReturnBike(bike)
}
// 切换模式（借用/归还）
const toggleMode = () => {
  isBorrowMode.value = !isBorrowMode.value
  if (isBorrowMode.value) {
    // 借用模式：筛选可用单车
    filterStatus.value = '可用'
    filterBikes()
    // 加载可用单车列表
    loadAvailableBikes()
  } else {
    // 归还模式：刷新我的借用列表
    loadMyBorrowedBikes()
  }
}

// 从列表中借用单车
const borrowBikeFromList = (bike: any) => {
  // 设置选中的单车
  selectedBike.value = bike
  selectedBikeOID = bike.OBJECTID

  // 显示借用确认对话框
  showBorrowConfirm()
}

// 关闭成功对话框
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
}
</script>

<template>
  <div class="borrow-container">
    <!-- 操作提示 -->
    <div class="operation-tip">
      <el-alert
        :title="isBorrowMode ? '点击地图上的单车图标可借用单车' : '请在下方列表中选择要归还的单车'"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <div class="main-content">
      <!-- 地图容器 -->
      <div id="bikeMapDiv" class="map-view"></div>

      <!-- 右侧功能面板 -->
      <div class="control-panel">
        <el-card class="control-card">
          <!-- 模式切换按钮移到面板顶部 -->
          <div class="mode-switch-bar">
            <el-button type="primary" @click="toggleMode" class="mode-button">
              {{ isBorrowMode ? '切换到归还模式' : '切换到借用模式' }}
            </el-button>
          </div>

          <div class="panel-title">
            <h2>{{ isBorrowMode ? '借用单车' : '归还单车' }}</h2>
          </div>

          <div class="panel-content">
            <!-- 借用模式下的筛选区域 -->
            <div class="filter-section" v-if="isBorrowMode">
              <el-select
                v-model="filterType"
                placeholder="按类型筛选"
                clearable
                @change="filterBikes"
                style="width: 100%"
              >
                <el-option label="普通单车" value="普通单车"></el-option>
                <el-option label="电动单车" value="电动单车"></el-option>
                <el-option label="折叠单车" value="折叠单车"></el-option>
              </el-select>
            </div>

            <!-- 借用模式下的可用单车列表 -->
            <div class="available-bikes" v-if="isBorrowMode">
              <h3>可用单车列表</h3>
              <el-divider />

              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>

              <el-empty
                v-else-if="availableBikes.length === 0"
                description="没有找到符合条件的单车"
              ></el-empty>

              <div v-else class="bike-list">
                <el-card v-for="bike in availableBikes" :key="bike.BikeId" class="bike-card">
                  <div class="bike-info">
                    <div class="bike-title">
                      <span>{{ bike.BikeType }}</span>
                      <el-tag size="small" type="success">ID: {{ bike.BikeId }}</el-tag>
                    </div>
                    <div class="bike-detail">地址: {{ bike.NowAddress }}</div>
                    <div class="bike-detail" v-if="bike.BikeType === '电动单车'">
                      电量: {{ bike.BatteryLevel }}
                    </div>
                    <div class="bike-actions">
                      <el-button type="primary" size="small" @click="borrowBikeFromList(bike)">
                        借用此单车
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 归还模式下的单车列表 -->
            <div class="borrowed-bikes" v-if="!isBorrowMode">
              <h3>我借用的单车</h3>
              <el-divider />

              <el-empty
                v-if="myBorrowedBikes.length === 0"
                description="您当前没有借用任何单车"
              ></el-empty>

              <div v-else class="bike-list">
                <el-card v-for="bike in myBorrowedBikes" :key="bike.BikeId" class="bike-card">
                  <div class="bike-info">
                    <div class="bike-title">
                      <span>{{ bike.BikeType }}</span>
                      <el-tag size="small" type="info">ID: {{ bike.BikeId }}</el-tag>
                    </div>
                    <div class="bike-detail">地址: {{ bike.NowAddress }}</div>
                    <div class="bike-detail">借用时间: {{ bike.BorrowTime }}</div>
                    <div class="bike-detail" v-if="bike.BikeType === '电动单车'">
                      电量: {{ bike.BatteryLevel }}
                    </div>
                    <div class="bike-actions">
                      <el-button type="success" size="small" @click="returnBike(bike)">
                        归还单车
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作成功提示对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      :title="successTitle"
      width="30%"
      custom-class="success-dialog"
    >
      <div class="success-content">
        <el-icon class="success-icon" size="large" color="#67C23A">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path
              fill="currentColor"
              d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm-55.808 536.384-99.52-99.584a38.4 38.4 0 1 0-54.336 54.336l126.72 126.72a38.272 38.272 0 0 0 54.336 0l262.4-262.464a38.4 38.4 0 1 0-54.272-54.336L456.192 600.384z"
            />
          </svg>
        </el-icon>
        <p>{{ successMessage }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeSuccessDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 归还位置选择对话框 -->
    <el-dialog
      v-model="showReturnLocationDialog"
      title="设置归还位置"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="return-location-content">
        <el-alert type="warning" :closable="false" show-icon>
          <template #title>
            <span class="location-alert-title">归还位置设置说明（必须按顺序完成）</span>
          </template>
          <p>
            <strong>步骤1：</strong
            >在地图上<strong>点击</strong>选择新的归还位置（必须先完成此步骤）
          </p>
          <p><strong>步骤2：</strong>在下方输入框中完善归还地址信息</p>
        </el-alert>

        <div class="location-status">
          <el-tag v-if="hasSelectedLocation" type="success" effect="dark"
            >✓ 已完成步骤1：位置选择</el-tag
          >
          <el-tag v-else type="info" effect="plain">⚠ 请先在地图上点击选择位置</el-tag>
        </div>

        <el-form label-position="top">
          <el-form-item label="归还地址">
            <el-input
              v-model="returnAddress"
              placeholder="请先在地图上选择位置，然后完善地址信息"
              :disabled="!hasSelectedLocation"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelLocationSelection">取消</el-button>
          <el-button
            type="primary"
            @click="confirmReturnBike"
            :disabled="!hasSelectedLocation || !returnAddress"
          >
            确认归还
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.borrow-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.main-content {
  display: flex;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  gap: 16px;
}

.map-view {
  flex: 1;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-height: 500px;
}

.control-panel {
  width: 350px;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.control-card {
  background-color: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
  font-weight: bold;
}

.bike-icon {
  width: 24px;
  height: 24px;
  background-color: #409eff;
  border-radius: 50%;
}

.filter-section {
  margin-bottom: 16px;
}

.control-buttons {
  margin: 16px 0;
}

.mode-button {
  width: 100%;
}

.operation-tip {
  position: absolute;
  top: 16px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  width: 80%;
  max-width: 600px;
}

.panel-content {
  height: calc(100vh - 220px);
  overflow-y: auto;
  padding-right: 5px;
}

.borrowed-bikes,
.available-bikes {
  margin-top: 16px;
}

.bike-card {
  margin-bottom: 12px;
  transition: all 0.3s;
}

.bike-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.bike-list {
  padding-right: 5px;
}

.loading-container {
  padding: 20px 0;
}

.mode-switch-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.panel-title {
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.panel-title h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.bike-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bike-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.bike-detail {
  font-size: 14px;
  color: #606266;
}

.bike-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-dialog .el-dialog__body {
  padding-top: 10px;
}

.return-location-content {
  padding: 10px 0;
}

.location-tip {
  margin-bottom: 16px;
  color: #606266;
  font-size: 14px;
}

.location-alert-title {
  font-weight: bold;
}

.location-status {
  margin: 16px 0;
  display: flex;
  justify-content: center;
}
</style>
